#include "SysLog.h"

#define LOG_FILE "SysLog.txt"
#define LOG_BAKFILE "SysLogBak.txt"
#define LOGFILE_MAXSIZE 60000


// 可变参数列表
int SysLog::SysLogOut(const char* logArg,...)
{
    char logStrBuff[500];
    va_list  valist;
    va_start(valist,logArg);
    vsnprintf(logStrBuff,sizeof(logStrBuff),logArg,valist);
    va_end(valist);
    
    LogBackupFunc();

    FILE * fp = NULL;

    if(access(LOG_FILE,F_OK) == -1)
    {
        fp = fopen(LOG_FILE,"w");
    }
    else
    {
        fp = fopen(LOG_FILE,"a");
    }

    // 获取当前系统时间
    char TimeStrBuf[64];
    strncpy(TimeStrBuf,GetTimeStrNow(),sizeof(TimeStrBuf));
    //printf("TimeStrBuf = %s",TimeStrBuf);
    //printf("logStrBuff = %s",logStrBuff);

    fprintf(fp,"##Time## %s ",TimeStrBuf);
    fprintf(fp,logStrBuff);

}


void SysLog::LogBackupFunc()
{
    FILE * fp = fopen(LOG_FILE,"r");
    if(NULL == fp)
    {
        printf("fopen %s error\n",LOG_FILE);
        return ;
    }

    // 偏移到末尾，取文件大小
    fseek(fp,0,SEEK_END);
    int size = ftell(fp);
    printf("%s size = %d\n",LOG_FILE,size);
    fseek(fp,0,SEEK_SET);

    fclose(fp);

    if(size>LOGFILE_MAXSIZE)
    {
        if(rename(LOG_FILE,LOG_BAKFILE) == -1)
        {
            SysLogOut("rename %s to %s error\n",LOG_FILE,LOG_BAKFILE);
            return ;
        }
    }

}

char * SysLog::GetTimeStrNow()
{
    time_t curTime;
    time(&curTime);

    return ctime(&curTime); 
}

